<template>
  <div class="chat-container">
    <div class="chat-header">
      <h1>AI 对话助手</h1>
      <div class="header-controls">
        <div class="function-selector">
          <label>Function Calls:</label>
          <div class="checkbox-group">
            <div class="checkbox-item" v-for="(func, key) in functionDefinitions" :key="key">
              <input 
                type="checkbox" 
                :id="`func-${key}`" 
                :value="key" 
                v-model="selectedFunctions"
                @change="onFunctionChange"
              >
              <label :for="`func-${key}`">{{ func.name }}</label>
            </div>
          </div>
        </div>
        <ApiKeyConfig v-model="API_KEY" />
      </div>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        :class="['message', message.role]"
      >
        <div class="message-content">
          <div class="message-text">{{ message.content }}</div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          <div v-if="message.functionCalls && message.functionCalls.length > 0" class="function-calls">
            <div v-for="(funcCall, idx) in message.functionCalls" :key="idx" class="function-call">
              <strong>Function Call:</strong> {{ funcCall.name }}
              <pre>{{ JSON.stringify(funcCall.arguments, null, 2) }}</pre>
            </div>
          </div>
        </div>
      </div>
      <div v-if="isLoading" class="message assistant loading">
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <div class="input-container">
        <textarea 
          v-model="userInput" 
          @keydown.enter.prevent="sendMessage"
          @keydown.shift.enter="addNewLine"
          placeholder="输入您的消息... (Shift+Enter 换行，Enter 发送)"
          rows="1"
          ref="textareaRef"
        ></textarea>
        <button 
          @click="sendMessage" 
          :disabled="!userInput.trim() || isLoading"
          class="send-button"
        >
          发送
        </button>
      </div>
      <div class="input-hint">
        当前选择的 Functions: 
        <span v-if="selectedFunctions.length === 0" class="function-name">无</span>
        <span v-else class="function-tags">
          <span 
            v-for="funcKey in selectedFunctions" 
            :key="funcKey" 
            class="function-tag"
          >
            {{ functionDefinitions[funcKey as keyof typeof functionDefinitions].name }}
          </span>
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import ApiKeyConfig from '../components/ApiKeyConfig.vue'

interface FunctionCall {
  name: string
  arguments: Record<string, any>
}

interface Message {
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
  functionCalls?: FunctionCall[]
}

const messages = ref<Message[]>([])
const userInput = ref('')
const isLoading = ref(false)
const selectedFunctions = ref<string[]>([])
const messagesContainer = ref<HTMLElement>()
const textareaRef = ref<HTMLTextAreaElement>()

// 模拟的 function call 定义
const functionDefinitions = {
  weather: {
    name: '获取天气',
    value: 'get_weather',
    description: '获取指定城市的天气信息',
    
  },
  gaode_nearby_places: {
    name: '附近位置获取',
    value: 'search_nearby_places',
    description: '获取指定位置附近的地点信息',
  },
 
  search: {
    name: '网络搜索',
    value: 'web_search',
    description: '在网络上搜索信息'
  }
}

const onFunctionChange = () => {
  console.log('选择的 Functions:', selectedFunctions.value)
}

const addNewLine = () => {
  userInput.value += '\n'
}

const formatTime = (timestamp: Date) => {
  return timestamp.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// API 配置
const API_URL = 'http://localhost:5000/api/qwen/chat'
const API_KEY = ref(localStorage.getItem('api_key') || '') // 从localStorage动态获取API密钥

// 真实的 AI 响应请求
const fetchAIResponse = async (userMessage: string): Promise<Message> => {
  let functionCallsInfo: FunctionCall[] = []
  
  // 准备请求数据
  let requestData: any = {
    message: userMessage,
    api_key: API_KEY.value
  }
  
  // 如果选择了特定的 function calls，添加到请求中
  if (selectedFunctions.value.length > 0) {
    requestData.function_calls = selectedFunctions.value.map(funcKey => {
      const funcDef = functionDefinitions[funcKey as keyof typeof functionDefinitions]
      return funcDef.value
    })
  }
  
  try {
    // 发送请求到 API
    const response = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    })
    console.log('API 响应:', response)
    if (!response.ok) {
      throw new Error(`API 请求失败: ${response.status}`)
    }
    
    const data = await response.json()
    console.log('API 响应数据:', data)
    // 处理 API 响应
    return {
      role: 'assistant',
      content: data.response || '抱歉，我无法处理您的请求。',
      timestamp: new Date(),
      functionCalls: data.function_calls || functionCallsInfo
    }
  } catch (error) {
    console.error('API 请求错误:', error)
    // 检查是否是CORS错误
    if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
      return {
        role: 'assistant',
        content: '跨域请求错误(CORS)：无法连接到API服务器。请确保后端服务器已启动并正确配置了CORS。',
        timestamp: new Date(),
        functionCalls: functionCallsInfo
      }
    }
    return {
      role: 'assistant',
      content: '抱歉，连接服务器时发生错误，请稍后重试。',
      timestamp: new Date(),
      functionCalls: functionCallsInfo
    }
  }
}

// 辅助函数：从消息中提取城市名
const extractCityFromMessage = (message: string): string => {
  const cities = ['北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '武汉']
  for (const city of cities) {
    if (message.includes(city)) {
      return city
    }
  }
  return '北京' // 默认城市
}

// 辅助函数：从消息中提取数学表达式
const extractMathFromMessage = (message: string): string => {
  const mathMatch = message.match(/[0-9+\-*/().\s]+/)
  return mathMatch ? mathMatch[0].trim() : '1+1'
}

const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return
  
  // 添加用户消息
  const userMessage: Message = {
    role: 'user',
    content: userInput.value.trim(),
    timestamp: new Date()
  }
  
  messages.value.push(userMessage)
  const currentInput = userInput.value.trim()
  userInput.value = ''
  
  await scrollToBottom()
  
  // 显示加载状态
  isLoading.value = true
  
  try {
    // 调用真实的 AI 响应 API
    const aiResponse = await fetchAIResponse(currentInput)
    messages.value.push(aiResponse)
  } catch (error) {
    console.error('发送消息失败:', error)
    messages.value.push({
      role: 'assistant',
      content: '抱歉，发生了错误，请稍后重试。',
      timestamp: new Date()
    })
  } finally {
    isLoading.value = false
    await scrollToBottom()
  }
}

// 初始化欢迎消息
onMounted(() => {
  messages.value.push({
    role: 'assistant',
    content: '您好！我是您的 AI 助手。您可以选择不同的 Function Call 功能来增强我的能力，或者直接与我对话。',
    timestamp: new Date()
  })
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 1400px;
  min-width: 800px;
  margin: 0 auto;
  padding: 1rem 2rem;
  box-sizing: border-box;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 1rem;
  border-bottom: 1px solid #4a14c7;
  margin-bottom: 1rem;
  color:#1976d2
}

.header-controls {
  display: flex;
  gap: 2rem;
  align-items: center;
}

.function-selector {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
  max-width: 500px;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  background-color: #e0e0e0;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #bdbdbd;
}

.checkbox-item:hover {
  background-color: #d0d0d0;
  border-color: #9e9e9e;
}

.checkbox-item input {
  cursor: pointer;
}

.checkbox-item label {
  cursor: pointer;
  font-size: 0.9rem;
}

.function-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.function-tag {
  background-color: #bbdefb;
  color: #0d47a1;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.85rem;
  font-weight: 500;
  border: 1px solid #90caf9;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  background-color: #f5f5f5;
  border-radius: 8px;
  margin: 0 auto;
  width: 100%;
  max-width: 1200px;
}

.message {
  max-width: 70%;
  padding: 1rem;
  border-radius: 8px;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.user {
  align-self: flex-end;
  background-color: #e3f2fd;
  color: #0d47a1;
}

.assistant {
  align-self: flex-start;
  background-color: white;
  color: #333;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.message-time {
  font-size: 0.8rem;
  color: #757575;
  align-self: flex-end;
}

.function-calls {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.function-call {
  background-color: #f0f4c3;
  padding: 0.5rem;
  border-radius: 4px;
  font-size: 0.9rem;
}

.function-call pre {
  margin: 0.5rem 0 0;
  white-space: pre-wrap;
  font-size: 0.85rem;
  background-color: rgba(255, 255, 255, 0.7);
  padding: 0.5rem;
  border-radius: 4px;
  overflow-x: auto;
}

.loading .typing-indicator {
  display: flex;
  gap: 0.5rem;
  padding: 1rem;
  justify-content: center;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #bdbdbd;
  border-radius: 50%;
  display: inline-block;
  animation: bounce 1.5s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes bounce {
  0%, 80%, 100% { transform: translateY(0); }
  40% { transform: translateY(-10px); }
}

.chat-input {
  margin-top: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  width: 100%;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}

.input-container {
  display: flex;
  gap: 0.75rem;
}

.input-container textarea {
  flex: 1;
  padding: 0.75rem 1rem;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  resize: none;
  font-family: inherit;
  font-size: 1rem;
  outline: none;
  transition: border-color 0.3s;
  min-height: 50px;
}

.input-container textarea:focus {
  border-color: #2196f3;
}

.send-button {
  padding: 0 2rem;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s;
}

.send-button:hover {
  background-color: #1976d2;
}

.send-button:disabled {
  background-color: #bdbdbd;
  cursor: not-allowed;
}

.input-hint {
  font-size: 0.85rem;
  color: #757575;
}

.function-name {
  font-weight: 500;
  color: #333;
}

/* 大屏幕适配 */
@media (min-width: 1600px) {
  .chat-container {
    max-width: 1600px;
    padding: 2rem 3rem;
  }
  
  .chat-messages,
  .chat-input {
    max-width: 1400px;
  }
  
  .message {
    max-width: 60%;
  }
}

/* 小屏幕适配 */
@media (max-width: 768px) {
  .chat-container {
    min-width: auto;
    padding: 0.5rem;
  }
  
  .chat-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .header-controls {
    width: 100%;
    flex-direction: column;
    gap: 1rem;
  }
  
  .message {
    max-width: 90%;
  }
  
  .checkbox-group {
    max-width: 100%;
  }
}
</style>